import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Space, Form, Input, Select, message, Modal, Upload } from 'antd';
import { PlusOutlined, UploadOutlined, DownloadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { UploadFile } from 'antd/es/upload/interface';
import { getPartyMemberList, deletePartyMember, importPartyMembers, exportPartyMembers } from '@/api/partyMember';
import type { PartyMember, PartyMemberQueryParams } from '@/api/partyMember';

const { Option } = Select;

const PartyMemberList: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<PartyMember[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const fetchData = async (params: PartyMemberQueryParams) => {
    try {
      setLoading(true);
      const result = await getPartyMemberList(params);
      setData(result.records);
      setTotal(result.total);
    } catch (error) {
      // 错误已在request.ts中处理
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData({
      current,
      size: pageSize,
      ...form.getFieldsValue(),
    });
  }, [current, pageSize]);

  const handleSearch = () => {
    setCurrent(1);
    fetchData({
      current: 1,
      size: pageSize,
      ...form.getFieldsValue(),
    });
  };

  const handleReset = () => {
    form.resetFields();
    setCurrent(1);
    fetchData({
      current: 1,
      size: pageSize,
    });
  };

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      onOk: async () => {
        try {
          await deletePartyMember(id);
          message.success('删除成功');
          fetchData({
            current,
            size: pageSize,
            ...form.getFieldsValue(),
          });
        } catch (error) {
          // 错误已在request.ts中处理
        }
      },
    });
  };

  const handleImport = async () => {
    if (fileList.length === 0) {
      message.warning('请选择要导入的文件');
      return;
    }

    try {
      const file = fileList[0].originFileObj as File;
      const errors = await importPartyMembers(file);
      if (errors && errors.length > 0) {
        message.warning(`导入完成，存在${errors.length}条错误`);
      } else {
        message.success('导入成功');
      }
      setUploadModalVisible(false);
      setFileList([]);
      fetchData({
        current,
        size: pageSize,
        ...form.getFieldsValue(),
      });
    } catch (error) {
      // 错误已在request.ts中处理
    }
  };

  const handleExport = async () => {
    try {
      const response = await exportPartyMembers({
        current,
        size: pageSize,
        ...form.getFieldsValue(),
      });
      const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = '党员信息.xlsx';
      link.click();
      window.URL.revokeObjectURL(url);
    } catch (error) {
      // 错误已在request.ts中处理
    }
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '所在班级',
      dataIndex: 'className',
      key: 'className',
    },
    {
      title: '职务',
      dataIndex: 'position',
      key: 'position',
    },
    {
      title: '职级',
      dataIndex: 'positionLevel',
      key: 'positionLevel',
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
      key: 'idCard',
    },
    {
      title: '标识号',
      dataIndex: 'identifier',
      key: 'identifier',
    },
    {
      title: '入党时间',
      dataIndex: 'joinDate',
      key: 'joinDate',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: PartyMember) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => navigate(`/party-members/${record.id}/edit`)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <Form
          form={form}
          layout="inline"
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="keyword" label="关键词">
            <Input placeholder="请输入姓名/身份证号/标识号" allowClear />
          </Form.Item>
          <Form.Item name="className" label="所在班级">
            <Input placeholder="请输入所在班级" allowClear />
          </Form.Item>
          <Form.Item name="position" label="职务">
            <Input placeholder="请输入职务" allowClear />
          </Form.Item>
          <Form.Item name="positionLevel" label="职级">
            <Select placeholder="请选择职级" allowClear style={{ width: 120 }}>
              <Option value="校级干部">校级干部</Option>
              <Option value="院级干部">院级干部</Option>
              <Option value="班级干部">班级干部</Option>
              <Option value="组长">组长</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" onClick={handleSearch}>
                查询
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Space style={{ marginBottom: 16 }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => navigate('/party-members/new')}
          >
            新增
          </Button>
          <Button
            icon={<UploadOutlined />}
            onClick={() => setUploadModalVisible(true)}
          >
            导入
          </Button>
          <Button
            icon={<DownloadOutlined />}
            onClick={handleExport}
          >
            导出
          </Button>
        </Space>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          onChange={(pagination) => {
            setCurrent(pagination.current || 1);
            setPageSize(pagination.pageSize || 10);
          }}
        />
      </Card>

      <Modal
        title="导入党员数据"
        open={uploadModalVisible}
        onOk={handleImport}
        onCancel={() => {
          setUploadModalVisible(false);
          setFileList([]);
        }}
      >
        <Upload
          fileList={fileList}
          onChange={({ fileList }) => setFileList(fileList)}
          beforeUpload={() => false}
        >
          <Button icon={<UploadOutlined />}>选择文件</Button>
        </Upload>
      </Modal>
    </div>
  );
};

export default PartyMemberList; 